<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input v-model="queryParams.type" placeholder="请输入类型" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input v-model="queryParams.category" placeholder="请输入分类" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="资料编号" align="center" key="id" prop="id" v-if="columns[0].visible" />
      <el-table-column label="资料名称" align="center" key="title" prop="title" v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column label="类型" align="center" key="type" prop="type" v-if="columns[2].visible" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" key="category" prop="category" v-if="columns[3].visible" :show-overflow-tooltip="true" />
      <el-table-column label="文件大小" align="center" key="size" prop="size" v-if="columns[4].visible" width="100">
        <template slot-scope="scope">
          <span>{{ formatFileSize(scope.row.size) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下载次数" align="center" key="downloadCount" prop="downloadCount" v-if="columns[5].visible" width="100" />
      <el-table-column label="状态" align="center" key="status" v-if="columns[6].visible">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[7].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:document:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:document:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改学习资料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row v-if="!form.id">
          <el-col :span="24">
            <el-form-item label="上传文件" prop="file">
              <FileUpload
                ref="fileUpload"
                v-model="form.filePath"
                :limit="1"
                :file-size="100"
                :file-type="['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar', '7z']"
                :is-show-tip="true"
                @input="handleFileChange"
              />
              <!-- 显示已选择的文件信息 -->
              <div v-if="form.filePath" class="file-info" style="margin-top: 10px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
                <p><strong>已选择文件：</strong>{{ getFileName(form.filePath) }}</p>
                <p><strong>文件大小：</strong>{{ form.size }}</p>
                <p><strong>文件类型：</strong>{{ form.filetype }}</p>
                <el-button size="mini" type="danger" @click="handleFileRemove">重新选择文件</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="form.type" placeholder="请输入类型" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-input v-model="form.category" placeholder="请输入分类" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件大小" prop="size">
              <el-input v-model="form.size" :placeholder="form.id ? '' : '文件大小将自动填充'" :readonly="!form.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件类型" prop="filetype">
              <el-input v-model="form.filetype" :placeholder="form.id ? '' : '文件类型将自动填充'" :readonly="!form.id" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入描述" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 学习资料详情对话框 -->
    <el-dialog title="学习资料详情" :visible.sync="viewOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="资料编号">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ viewForm.title }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ viewForm.type || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ viewForm.category || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="文件大小">{{ formatFileSize(viewForm.size) }}</el-descriptions-item>
        <el-descriptions-item label="文件类型">{{ viewForm.filetype }}</el-descriptions-item>
        <el-descriptions-item label="下载次数">{{ viewForm.downloadCount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.sys_normal_disable" :value="viewForm.status" />
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建者">{{ viewForm.createBy }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(viewForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新者">{{ viewForm.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ viewForm.description || '暂无描述' }}</el-descriptions-item>
        <el-descriptions-item label="文件路径" :span="2">{{ viewForm.filePath }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDownload(viewForm)">下载文件</el-button>
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的资料数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDocument, getDocument, delDocument, addDocument, updateDocument, changeDocumentStatus, downloadDocument } from "@/api/system/document"
import { getToken } from "@/utils/auth"
import FileUpload from "@/components/FileUpload"

export default {
  name: "Document",
  dicts: ['sys_normal_disable', 'document_type', 'document_category'],
  components: { FileUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学习资料表格数据
      documentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      viewOpen: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 详情表单参数
      viewForm: {},
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/study/document/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        type: undefined,
        category: undefined,
        status: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `资料编号`, visible: true },
        { key: 1, label: `资料名称`, visible: true },
        { key: 2, label: `类型`, visible: true },
        { key: 3, label: `分类`, visible: true },
        { key: 4, label: `文件大小`, visible: true },
        { key: 5, label: `下载次数`, visible: true },
        { key: 6, label: `状态`, visible: true },
        { key: 7, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '标题长度必须介于 2 和 100 之间', trigger: 'blur' }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "blur" },
          { min: 1, max: 50, message: '类型长度必须介于 1 和 50 之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询学习资料列表 */
    getList() {
      this.loading = true
      listDocument(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.documentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        description: undefined,
        type: "",
        category: "",
        filetype: undefined,
        filePath: undefined,
        size: undefined,
        status: "0"
      }
      this.resetForm("form")
      // 清空FileUpload组件的值
      this.$nextTick(() => {
        this.form.filePath = ""
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加学习资料"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDocument(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改学习资料"
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      getDocument(row.id).then(response => {
        this.viewForm = response.data
        this.viewOpen = true
      })
    },
    /** 下载按钮操作 */
    handleDownload(row) {
//      url: process.env.VUE_APP_BASE_API + "/system/user/importData"
//      const url = process.env.VUE_APP_BASE_API +row.
//      const link = document.createElement('a')
//      link.href = url
//      link.download = row.title + '.' + row.filetype
//      link.click()
//      window.URL.revokeObjectURL(url)
      downloadDocument(row.filePath).then(response => {
        const blob = new Blob([response])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = row.title + '.' + row.filetype
        link.click()
        window.URL.revokeObjectURL(url)
        this.$modal.msgSuccess("下载成功")
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
                  // 检查是否选择了文件（新增时）
        if (!this.form.id && !this.form.filePath) {
          this.$modal.msgError("请先选择要上传的文件")
          return
        }
        
                // 检查是否填写了资料名称
        if (!this.form.title) {
          this.$modal.msgError("请填写资料名称")
          return
        }
        
        // 检查是否填写了类型（必填）
        if (!this.form.type) {
          this.$modal.msgError("请填写类型")
          return
        }
        
        // 检查是否填写了文件大小（可选，因为FileUpload组件不提供文件大小）
        if (!this.form.size) {
          this.form.size = 0 // 设置为默认值
        }
        
        // 检查是否填写了文件类型（自动填充）
        if (!this.form.id && !this.form.filetype) {
          this.$modal.msgError("请选择文件")
          return
        }
        
        // 检查是否填写了文件路径（自动填充）
        if (!this.form.id && !this.form.filePath) {
          this.$modal.msgError("请选择文件")
          return
        }
        
        // 检查是否填写了状态（有默认值）
        if (!this.form.status) {
          this.form.status = "0" // 设置为默认启用状态
        }
        
        // 检查是否填写了描述（可选）
        if (!this.form.description) {
          this.form.description = "" // 设置为空字符串
        }
        
        // 检查是否填写了文件大小（数字格式）
        if (this.form.size && typeof this.form.size === 'string') {
          // 如果是字符串格式，转换为数字
          const sizeMatch = this.form.size.match(/(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)/i)
          if (sizeMatch) {
            const size = parseFloat(sizeMatch[1])
            const unit = sizeMatch[2].toUpperCase()
            // 转换为字节
            const multipliers = { B: 1, KB: 1024, MB: 1024 * 1024, GB: 1024 * 1024 * 1024, TB: 1024 * 1024 * 1024 * 1024 }
            this.form.size = Math.round(size * multipliers[unit])
          }
        }
        
        // 检查是否填写了文件类型（大写）
        if (this.form.filetype) {
          this.form.filetype = this.form.filetype
        }
        
        // 检查是否填写了标题（去除首尾空格）
        if (this.form.title) {
          this.form.title = this.form.title.trim()
        }
        
        // 检查是否填写了类型（去除首尾空格）
        if (this.form.type) {
          this.form.type = this.form.type.trim()
        }
        
        // 检查是否填写了分类（去除首尾空格）
        if (this.form.category) {
          this.form.category = this.form.category.trim()
        }
        
        // 检查是否填写了描述（去除首尾空格）
        if (this.form.description) {
          this.form.description = this.form.description.trim()
        }
        
        // 检查是否填写了文件路径（去除首尾空格）
        if (this.form.filePath) {
          this.form.filePath = this.form.filePath.trim()
        }
        
        if (this.form.id != undefined) {
            // 修改操作
            updateDocument(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // 新增操作
            addDocument(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const documentIds = row.id || this.ids
      this.$modal.confirm('是否确认删除学习资料编号为"' + documentIds + '"的数据项？').then(function() {
        return delDocument(documentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('study/document/export', {
        ...this.queryParams
      }, `document_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学习资料导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('study/document/importTemplate', {
      }, `document_template_${new Date().getTime()}.xlsx`)
    },
    // 文件变化处理
    handleFileChange(filePath) {
      if (filePath && !this.form.id) {
        // 只在新增时自动填充
        const fileName = this.getFileName(filePath)
        // 自动填充文件名
        this.form.title = fileName.replace(/\.[^/.]+$/, "") // 移除文件扩展名
        // 自动填充文件类型
        this.form.filetype = fileName.split('.').pop()
        // 自动填充文件路径（使用服务器返回的url）
        this.form.filePath = filePath

        // 尝试从FileUpload组件获取文件大小
        this.$nextTick(() => {
          if (this.$refs.fileUpload && this.$refs.fileUpload.fileList && this.$refs.fileUpload.fileList.length > 0) {
            const fileInfo = this.$refs.fileUpload.fileList[0]
            if (fileInfo.size) {
              this.form.size = this.formatFileSize(fileInfo.size)
            } else {
              this.form.size = 0
            }
          } else {
            this.form.size = 0
          }
        })
        
        // 根据文件扩展名自动填充类型
        const extension = fileName.split('.').pop().toLowerCase()
        if (['pdf', 'doc', 'docx', 'txt'].includes(extension)) {
          this.form.type = '文档'
        } else if (['xls', 'xlsx'].includes(extension)) {
          this.form.type = '表格'
        } else if (['ppt', 'pptx'].includes(extension)) {
          this.form.type = '演示'
        } else if (['zip', 'rar', '7z'].includes(extension)) {
          this.form.type = '压缩包'
        } else {
          this.form.type = '其他'
        }
        
        // 显示成功提示
        this.$modal.msgSuccess("文件上传成功，信息已自动填充，请确认后点击确定按钮")
      }
    },


    // 文件移除处理
              // 文件移除处理
    handleFileRemove() {
      // 清空相关字段
      this.form.title = ""
      this.form.size = ""
      this.form.filetype = ""
      this.form.filePath = ""
      this.form.type = ""
      this.form.category = ""
      // 清空FileUpload组件的值
      this.$nextTick(() => {
        this.form.filePath = ""
      })
      this.$modal.msgInfo("文件已移除，可以重新选择文件")
    },
    // 获取文件名
    getFileName(filePath) {
      if (filePath.lastIndexOf("/") > -1) {
        return filePath.slice(filePath.lastIndexOf("/") + 1)
      } else {
        return filePath
      }
    },

    // 导入文件上传进度处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 导入文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 学习资料状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"学习资料吗？').then(function() {
        return changeDocumentStatus(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  }
}
</script>

<style scoped>
.el-upload-dragger {
  width: 100%;
}

.el-form-item__label {
  font-weight: 500;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}

.el-upload__text {
  color: #606266;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}
</style>
